import modelExtend from 'dva-model-extend'
import { detail, approve, deny } from './services/financialReceipt'
import { lwjPageModel } from 'utils/model'
import pathToRegexp from 'path-to-regexp';
import { routerRedux } from 'dva/router';

export default modelExtend(lwjPageModel, {
  namespace: 'receiptAudit',
  state: {
    currentItemDetail: {},
    detailUrl: ""
  },
  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(({ pathname }) => {
        const match = pathToRegexp('/receipt/audit/:id').exec(pathname);
        if (match) {
          dispatch({
            type: 'detailSuccess', payload: { currentItemDetail: {} }
          })
          const id = match[1];
          dispatch({
            type: 'audit',
            payload: {
              id: id
            }
          })
        }
      })
    }
  },
  effects: {
    * audit({
      payload
    }, { select, call, put }) {
      const data = yield call(detail, payload.id);
      yield put({
        type: 'detailSuccess', payload: { currentItemDetail: data.result }
      })
    },
    * approve({
      payload
    }, { select, call, put }) {
      const params = { ...payload, "id": payload.id }
      const data = yield call(approve, params);
      if (data.code === 0) {
        yield put({
          type: 'detailSuccess', payload: { currentItemDetail: data, detailUrl: "/receipt/detail/" + data.result }
        })
        yield put({
          type: 'showSuccess',payload:{}
        })
      }

    },
    * showSuccess({
      payload
    }, { select, call, put }) {
      const detailUrl = yield select(({ receiptAudit }) => receiptAudit.detailUrl);
      yield put(routerRedux.push('/success', { listUrl: '/receipt', detailUrl: detailUrl }));
    },
    * deny({
      payload
    }, { select, call, put }) {
      const params = { ...payload, "id": payload.id }
      const data = yield call(deny, params);
      if(data.code===0){
        yield put({
          type: 'detailSuccess', payload: { currentItemDetail: data, detailUrl: "/receipt/detail/" + data.result }
        })
        yield put({
          type: 'showSuccess',payload:{}
        })
      }

    }
  },
  reducers: {
    detailSuccess(state, { payload }) {
      return {
        ...state,
        ...payload
      }
    }
  }
})
